/*!
 * Promise and asynchronous observer libraries
 * https://github.com/kriskowal/asap
 */

let domain // The domain module is executed on demand
const hasSetImmediate = typeof setImmediate === 'function'

// Use the fastest means possible to execute a task in its own turn, with
// priority over other events including network IO events in Node.js.
//
// An exception thrown by a task will permanently interrupt the processing of
// subsequent tasks. The higher level `asap` function ensures that if an
// exception is thrown by a task, that the task queue will continue flushing as
// soon as possible, but if you use `rawAsap` directly, you are responsible to
// either ensure that no exceptions are thrown from your task, or to manually
// call `rawAsap.requestFlush` if an exception is thrown.
export function rawAsap(task) {
  if(!queue.length) {
    requestFlush()
    flushing = true
  }
  // Avoids a function call
  queue[queue.length] = task
}

const queue = []
// Once a flush has been requested, no further calls to `requestFlush` are
// necessary until the next `flush` completes.
let flushing = false
// The position of the next task to execute in the task queue. This is
// preserved between calls to `flush` so that it can be resumed if
// a task throws an exception.
let index = 0
// If a task schedules additional tasks recursively, the task queue can grow
// unbounded. To prevent memory excaustion, the task queue will periodically
// truncate already-completed tasks.
let capacity = 1024

// The flush function processes all tasks that have been scheduled with
// `rawAsap` unless and until one of those tasks throws an exception.
// If a task throws an exception, `flush` ensures that its state will remain
// consistent and will resume where it left off when called again.
// However, `flush` does not make any arrangements to be called again if an
// exception is thrown.
function flush() {
  while(index < queue.length) {
    var currentIndex = index
    // Advance the index before calling the task. This ensures that we will
    // begin flushing on the next task the task throws an error.
    index = index + 1
    queue[currentIndex].call()
    // Prevent leaking memory for long chains of recursive calls to `asap`.
    // If we call `asap` within tasks scheduled by `asap`, the queue will
    // grow, but to avoid an O(n) walk for every task we execute, we don't
    // shift tasks off the queue after they have been executed.
    // Instead, we periodically shift 1024 tasks off the queue.
    if(index > capacity) {
      // Manually shift all values starting at the index back to the
      // beginning of the queue.
      for(var scan = 0, newLength = queue.length - index; scan < newLength; scan++) {
        queue[scan] = queue[scan + index]
      }
      queue.length -= index
      index = 0
    }
  }
  queue.length = 0
  index = 0
  flushing = false
}

rawAsap.requestFlush = requestFlush

function requestFlush() {
  // `setImmediate` is slower that `process.nextTick`, but `process.nextTick`
  // cannot handle recursion.
  // `requestFlush` will only be called recursively from `asap.js`, to resume
  // flushing after an error is thrown into a domain.
  // Conveniently, `setImmediate` was introduced in the same version
  // `process.nextTick` started throwing recursion errors.
  if(flushing && hasSetImmediate) {
    setImmediate(flush)
  } else {
    process.nextTick(flush)
  }
}

const freeTasks = []

/**
 * Calls a task as soon as possible after returning, in its own event, with
 * priority over IO events. An exception thrown in a task can be handled by
 * `process.on("uncaughtException") or `domain.on("error")`, but will otherwise
 * crash the process. If the error is handled, all subsequent tasks will
 * resume.
 *
 * @param {{call}} task A callable object, typically a function that takes no
 * arguments.
 */
export default function asap(task) {
  let rawTask
  if(freeTasks.length) {
    rawTask = freeTasks.pop()
  } else {
    rawTask = new RawTask()
  }
  rawTask.task = task
  rawTask.domain = process.domain
  rawAsap(rawTask)
}

function RawTask() {
  this.task = null
  this.domain = null
}

RawTask.prototype.call = function() {
  if(this.domain) {
    this.domain.enter()
  }
  let threw = true
  try {
    this.task.call()
    threw = false
    // If the task throws an exception (presumably) Node.js restores the
    // domain stack for the next event.
    if(this.domain) {
      this.domain.exit()
    }
  } finally {
    // We use try/finally and a threw flag to avoid messing up stack traces
    // when we catch and release errors.
    if(threw) {
      // In Node.js, uncaught exceptions are considered fatal errors.
      // Re-throw them to interrupt flushing!
      // Ensure that flushing continues if an uncaught exception is
      // suppressed listening process.on("uncaughtException") or
      // domain.on("error").
      rawAsap.requestFlush()
    }
    // If the task threw an error, we do not want to exit the domain here.
    // Exiting the domain would prevent the domain from catching the error.
    this.task = null
    this.domain = null
    freeTasks.push(this)
  }
}
